import React from 'react';
import { observer, inject} from 'mobx-react';
import { withRouter, Route } from 'react-router-dom';
import { Form, SelectPage, RouteLayout, } from 'weaver-mobile-page';
import { List, Icon, InputItem, Bubble, Button, Tools, Switch, DatePicker, Select, Modal} from 'weaver-mobile';
import { routeBackToUpperlevel } from 'weaver-mobile-page';
import { toJS } from 'mobx'
import * as Api from '../../api/create';
import Remind from './remind';
import RepeatType from './repeatType';
import EndRepeat from './endRepeat';
import RouteCreate from './route.js';
const alert = Modal.alert;
const { FormItem } = List;
const getLabel = Tools.getLabel;
const nowTimeStamp = Date.now();
const now = new Date(nowTimeStamp);

const store = [
  'createStore',
  'calendarStore',
  'viewWorkplanStore',
];

@routeBackToUpperlevel
@inject(...store)
@withRouter
@observer
class Create extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      beginDate: now,
      endDate: '',
      repeatOption: '1',
      checked: 0,
      date: '',
      value: null,
      endrepeat: getLabel(389715,'永不'),
      endrepeatOptions: [],
      beginDateStr: '',
      endDateStr: '',
      isedit: false,
      workPlanTypeOptions: 0,
      singleCreate: false,
      urlParams:{}
    }
  }

  componentWillMount() {
    const { isEdit } = this.props.createStore;
    if(!isEdit){
      const urlParams =  this.getUrlParams()
      let fromType = urlParams.fromType;
      const { setParams } = this.props.createStore;
      if(fromType){
        setParams({fromType:fromType})
      }else{
        setParams({fromType:''})
      } 
    }
  }
  
  componentDidMount() {
    const urlParams =  this.getUrlParams();
    let pathName = this.props.location.pathname
    const { getCreateWorkplanBaseData,getEditWorkplanBaseData,setParams,isEdit,startDateString,endDateString } = this.props.createStore;
    const { selectDate,userID, } = this.props.calendarStore;
    let fromType = urlParams.fromType;
    this.setState({urlParams:urlParams})
    let selectedUserId = urlParams.selectedUserId;
    let workPlanTypeOptions = urlParams.workPlanTypeOptions;
    let crmIDs = urlParams.crmIDs;
    
    
    workPlanTypeOptions && this.setState({workPlanTypeOptions: workPlanTypeOptions});
    if(selectedUserId || workPlanTypeOptions) {
      this.setState({singleCreate: true});
    }
    
    if((selectedUserId || crmIDs || fromType) && !isEdit) {
      /* 查看时支持route形式： 
        create?selectedUser=**&&workPlanTypeOptions=**&&crmIDs=** 
     */
      fromType && fromType === 'crm' ? getCreateWorkplanBaseData({selectUser: selectedUserId,crmid: crmIDs,fromType: 'crm'},this.editCondition) 
                                     : getCreateWorkplanBaseData({selectUser: selectedUserId,crmid: crmIDs},this.editCondition);
    }else{
      if(isEdit) {
        const {fromtype} = this.props.viewWorkplanStore
        fromtype ? getEditWorkplanBaseData({fromType: fromtype},this.editCondition) : getEditWorkplanBaseData({},this.editCondition);
        this.setState({beginDateStr: startDateString,endDateStr: endDateString});
      }else{
        if(localStorage.workplanTabs && (localStorage.workplanTabs === '2' || localStorage.workplanTabs === '3')) {
          getCreateWorkplanBaseData({selectUser: userID},this.editCondition);
        }else{
          let pathstr = window.location.hash && window.location.hash.split('#');
          if(pathstr[1].indexOf('calendar/appointhrm') > 0){
            getCreateWorkplanBaseData({selectUser: userID},this.editCondition);
          }else{
            getCreateWorkplanBaseData({},this.editCondition);
          }
        }
      }
    }
    setParams({startDateString: selectDate, endDateString: selectDate});
  }


  componentWillUnmount() {
    const { setParams,initRepeatInfo } = this.props.createStore;
    initRepeatInfo(); // 清空数据
    setParams({isEdit: false})
  }

  getUrlParams = ()=>{
    const URL = this.props.location.search ? this.props.location.search.split('?')[1] : ''
    const url = URL.length > 0 ? URL.split('&') : [];
    const Arr = this.getQuery(url);
    let selectedUserId = this.props.location.search ? Arr['selectedUser'] : this.props.location&&this.props.location.query&&this.props.location.query.selectedUser;
    let workPlanTypeOptions = this.props.location.search ? Arr['workPlanTypeOptions'] : this.props.location&&this.props.location.query&&this.props.location.query.workPlanTypeOptions;
    let crmIDs = this.props.location.search ? Arr['crmIDs'] : this.props.location&&this.props.location.query&&this.props.location.query.crmIDs;
    let fromType = this.props.location.search ? Arr['fromType'] : this.props.location&&this.props.location.query&&this.props.location.query.fromType;
    const urlParams = {
      selectedUserId:selectedUserId,
      workPlanTypeOptions:workPlanTypeOptions,
      crmIDs:crmIDs,
      fromType:fromType
    }
    const { setParams } = this.props.createStore;
    const { pathname } = this.props.location;
    let urlP =  {
      ...Arr,
      isSingle: ["/create", "/detail/create"].some(v => v === pathname),
    };
    setParams({ urlCreateParams: urlP });
    return urlParams
  }

  getQuery = (search)=>{
    let params ={}
    search.map((v,index)=>{
      const tempV = v.split('=');
      params[tempV[0]] = tempV[1];
      return '';
    });
    return params
  }

  submit = () => {
    const { form, workpalnID, meetingID, repeatInfo, isEdit, memberConflictChk, createInfo, isOpenSecret } = this.props.createStore;
    // form.updateField('remindImmediately',this.state.checked);
    const {urlParams} =  this.state;
    let formParams = form.formParams;
    let temp = formParams.planName === '' || formParams.workPlanType === '' || formParams.endDateTime === '' || formParams.beginDateTime === '' || formParams.memberIDsspan === '';
    let remindTemp = formParams.remindImmediately === false && formParams.remindBeforeStart === '' && formParams.remindBeforeEnd === '';
    let begintime = formParams.beginDateTime;
    let endtime = formParams.endDateTime;
    // let params = {...form.formParams,...toJS(repeatInfo),workid: workpalnID, meetingId: meetingID};
    const { workPlanTypeOptions,checked } = this.state;
    let startAndEndNoremid = formParams.remindBeforeStart == formParams.remindBeforeEnd && formParams.remindBeforeStart == '0'; // 开始前结束前同时为不提醒
    if(workPlanTypeOptions){
      formParams['workPlanType'] = workPlanTypeOptions;
    }
    Object.keys(formParams).forEach(key => {
      if(key === 'remindImmediately') {
        formParams[key] = this.state.checked;
      }
    });
    let params = {...formParams,...toJS(repeatInfo),workid: isEdit?workpalnID:'', meetingId: meetingID};
    let canSave = true;
    if(begintime >= endtime){
      Bubble.error(getLabel(130211,' 结束时间必须大于开始时间!'), 1)
      canSave = false;
    }else if(formParams.remindType !== ''){
      if(temp || formParams.planName.replace(/\s/g,'') === ''){
        Bubble.error(getLabel(387627,'必填项没有填写!'), 1)
        canSave = false;
      }else if(!checked && (formParams.remindTimeBeforeEnd === '') && (formParams.remindTimeBeforeStart === '') || (formParams.remindImmediately == 0&&startAndEndNoremid) 
                || (String(formParams.remindImmediately)==='undefined'&&startAndEndNoremid)){
        Bubble.error(getLabel(501389,'开始前或结束前提醒时间未选择!'), 1)
        canSave = false;
      }
    }else if(isOpenSecret && (formParams.secretLevel ==='' || formParams.secretLevel === undefined)){
      Bubble.error(getLabel(387627,'必填项没有填写!'), 1)
      canSave = false;
    }else if(urlParams.fromType === 'crm' && (formParams.crmIDs ==='' || formParams.crmIDs === undefined)){
      Bubble.error(getLabel(387627,'必填项没有填写!'), 1)
      canSave = false;
    }else{
      if(remindTemp || temp || formParams.planName.replace(/\s/g,'') === ''){ // 去除标题中的空格
        Bubble.error(getLabel(387627,'必填项没有填写!'), 1)
        canSave = false;
      }
    }
    if(memberConflictChk ) { // memberConflictChk存在时,冲突校验
      if(canSave === true && memberConflictChk === 0){
        this.save(params);
      } else if(canSave === true && memberConflictChk === 1){
        let params4check = {
          workid:params.workid,
          beginDateTime:params.beginDateTime,
          endDateTime:params.endDateTime,
          resourceId:params.memberIDs,
        }
        this.checkMember(params4check,params);
      }
    }else{
      if(canSave === true) {
        this.save(params);
      }
    }

    return false;
  }

  save = (params) => {
    const { form, setParams,isEdit,oldMemberIds } = this.props.createStore;
    const { workPlanTypeOptions } = this.state;
    let temp = form.formParams.remindTimeBeforeEnd === '' && form.formParams.remindTimeBeforeStart === '';
    setParams({createDisabled: true});
    params = {...params,from:'workplan'}
    if(oldMemberIds != params.memberIDs){
      params = {...params,needCheck:1}
    }else{
      params = {...params,needCheck:0}
    }
    if(params.remindType === '') {// 提醒方式未选择，清除开始、结束前提醒时间
      params = {
        ...params,
        remindBeforeStart: '0',
        remindBeforeEnd: '0',
        remindTimeBeforeStart: '',
        remindTimeBeforeEnd: '',
      };
    }
    Api.createWorkplan(params).then(res => {
      // setParams({createDisabled: false});
      let doSuccess = (workplanid)=>{
        const { freshCalendar } = this.props.calendarStore;
        const { urlCreateParams } = this.props.createStore;
        typeof freshCalendar === 'function' && freshCalendar(true);
        
        Bubble.success(getLabel(18758,'保存成功'), 1);
        if(urlCreateParams.isClose === 'true') {
          window.em&&window.em.closeWindow&&window.em.closeWindow();
        } else if(urlCreateParams.isClose === 'false') {
          setParams({createDisabled: false});
          this.props.history.push(`/detail/index?fromCreate=true&isClose=false&workplanId=${workplanid}`);
        } else {
          setTimeout(() => {
            if(workPlanTypeOptions) {
              this.props.history.go(-1);
            }else if(localStorage && localStorage.singleDetail === 'true'){
              this.props.history.push('/detail/index')
              const {  isSingelViewWorkplan,fromType, setParams:viewSetPar } = this.props.viewWorkplanStore;
              if (isSingelViewWorkplan && fromType === 'crm') {
                viewSetPar({otherModuleCloseWP:true})
              }
            }else{
              if(this.props.history.location && this.props.history.location.pathname.indexOf('detail') > 0) {
                // 编辑后跳转详情页
                let p = this.props.history.location.pathname.split('/create')
                if(p[0] && p[0].indexOf('workPlanViewList') > -1) {
                  let t = p[0].split('workPlanViewList');
                  p[0] = t[0] + '/workPlanViewList';
                }
                this.props.history.push(`${p[0]}`)
              }else{
                this.props.history.go(-1);
              }
            }
            setParams({createDisabled: false});
          }, 1000);
        }
      }
      if(res.api_status) {
        if(!res.error){
          doSuccess(res.workplanid);
        }else if(res.error && res.outList){
          // let titleMsg = <span style={{fontWeight:'bold'}}>{getLabel(504401, '以下日程冲突，确定要继续保存吗？') }</span>;
          let cont = <div>{res.error}{getLabel(510186,'如果继续保存，以上人员将会从“接收人”中删除！')}</div>
          let memberhrmMsg=<div style={{maxHeight:'60px',overflowY:'auto',WebkitOverflowScrolling: 'touch'}}>
              { <div>{cont}</div>}
          </div>
          alert('', memberhrmMsg, [
            {
              key: 'default',
              text: getLabel(386789,'取消'), 
              style: 'default' 
            },
            {
              key: 'save',
              text: getLabel(386788,'确定'), 
              onPress: () => {
                params = {...params,needCheck:0}
                Api.createWorkplan(params).then(res2 => {
                  if(res2.api_status) {
                    doSuccess(res2.workplanid);
                  }else{
                    setParams({createDisabled: false});
                    Bubble.error(getLabel(22620,'保存失败'), 1)
                  }
                }, (res) => {
                  setParams({createDisabled: false});
                })
              } 
            },
          ])
        }
      }else{
        setParams({createDisabled: false});
        Bubble.error(getLabel(22620,'保存失败'), 1)
      } 
    }, (res) => {
      setParams({createDisabled: false});
    });
  }

  checkMember = (params4check,params)=>{
    Api.workplanMemberChk(params4check).then((ret)=>{
      if(ret.chkstatus){
        this.doMemberTip(ret,params)
      }else{
        this.save(params)
      }
    })
  }

  doMemberTip = (result, params) => {
    let that = this
    let conflictMsg = '';
    let cont = result.hrms.map((e) => {
      return <div>{e}</div>
    })

    let titleMsg = <span style={{fontWeight:'bold'}}>{getLabel(504401, '以下日程冲突，确定要继续保存吗？') }</span>;
    
    let memberhrmMsg=<div style={{maxHeight:'60px',overflowY:'auto',WebkitOverflowScrolling: 'touch'}}>
        {result.hrms.length > 0 ? <div>{cont}</div> : ''}
    </div>

    if (result.cansub === true) {
      alert(titleMsg, memberhrmMsg, [
        {
          key: 'default',
          text: getLabel(386789,'取消'), 
          style: 'default' 
        },
        {
          key: 'save',
          text: getLabel(386788,'确定'), 
          onPress: () => {
            that.save(params)
          } 
        },
      ])
    } else {
      alert(getLabel(504398, '日程冲突不能保存'), memberhrmMsg, [
        {
          key: 'default',
          text: getLabel(386788,'确定'), 
          style: 'default' 
        },
      ])
    }
  }

  onclick = (e) => {
    const { layout, setParams } = this.props.createStore;
    setParams({idname: e.target.id })
    e.target.attributes && e.target.attributes.time && setParams({currentTime: e.target.attributes.time.nodeValue })
    this.props.history.push(layout.path)
  }

  getDataKey = (data) => {
    const { form, setParams } = this.props.createStore;
    let key = [];
    let va = {};
    data && data.forEach(res => {
      key.push(res.key)
    })
    va = key.toString()
    form.updateField('remindType',va)
    setParams({remidOptions: key})
  }

  immediateRemind = (check) => {
    const { form } = this.props.createStore;
    if(check){
      form.updateField('remindImmediately','1');
      this.setState({checked: 1});
    }else{
      form.updateField('remindImmediately','0');
      this.setState({checked: 0});
    }
  }

  setTime = (date,fieldLabel) => {
    const { form,setParams } = this.props.createStore;
    if(fieldLabel === 'beginDateTime') {
      form.updateField('beginDateTime',date);
      setParams({startDateString: ''})
      this.setState({beginDateStr: date})
    }
    if(fieldLabel === 'endDateTime') {
      form.updateField('endDateTime',date);
      setParams({endDateString: ''})
      this.setState({endDateStr: date})
    }
  }

  changeTimeTOLabel = (data, type) => {
    // remindBeforeEnd, remindBeforeStart: 0-不提醒 1-提醒
    // remindBeforeEnd=0/remindBeforeStart=0  不提醒
    // remindBeforeEnd=1/remindBeforeStart=1, remindTimeBeforeEnd=0/remindTimeBeforeStart=0    正点
    const change = (param) => {
      let str = '';
      let hour = Math.floor(param/60) === 0 ? '' : Math.floor(param/60)+getLabel(391,'小时');
      let minte = param%60 ? param%60 + getLabel(15049,'分钟') : '';
      str = hour + minte;
      return str;
    }
    if (type == 0) {
      return data;
    } else {
      if(typeof(data) === 'number'){
          return change(data)
      }else{
        if(parseInt(data,10) >= 0) {
            return change(data)
        }else{
          if(data === getLabel(390083,'正点')) {
            return '0'+getLabel(15049,'分钟');
          }else{
            return data;
          }
        }
      }
    }
  }

  focusRepeatType = (type) => {
    this.setState({repeatOption: type[0].key}) 
  }

  getRepeatType = (type) => {
    const { setParams,repeatLayout } = this.props.createStore;
    const { form } = this.props.createStore

    setParams({repeatType: type.key})
    form.updateField('repeatType',type.key);
    type.key === '5' && this.props.history.push(repeatLayout.path)
  }

  updateRepeatType = (params) => {
    const { form } = this.props.createStore;
    if(params && params[0]) {
      if(params[0].key != '0') { // 周期日程
        this.immediateRemind(false);
      }
      form.updateField('repeatType',params[0].key);
    };
  }
  
  onChange = (paramsObj,value) => {
    const domkey = paramsObj.domkey[0];
    const { form , setOldSecretLevel,oldSecretLevel } = this.props.createStore;
    if (domkey === 'secretLevel') {
      //密级等级是否小于当前使用等级
      const secretLevel = value
      if(parseInt(secretLevel,10) > parseInt(oldSecretLevel,10)){
        alert(getLabel(15172, '系统提示'), getLabel(500701,'【密级】级别已更改且小于上次选择，文档、流程资源会被清空'), [
          { 
            text: getLabel(386789,'取消'), 
            onPress: () => {
              form.updateField(domkey,oldSecretLevel)
            },
             style: 'default' },
          { 
            text: getLabel(386788,'确定'), 
            onPress: () => { 
              form.updateField(domkey,value)
              setOldSecretLevel(value)
              form.updateFields({
              //   relatedprj:[{
              //   id:'',
              //   name:''
              // }],
              // relatedcus:[{
              //   id:'',
              //   name:''
              // }],
              docIDs:{value: [{
                id:'',
                name:''
              }]},
              requestIDs:{value: [{
                id:'',
                name:''
              }]},
            });
            this.editCondition();

            }},
        ]);
      }else{
        form.updateField(domkey,value)  
        setOldSecretLevel(value)
      }
      this.editCondition();
    }else{
      form.updateField(domkey,value)
    }
  };


  getEndRepeat = (params) => {
    const {endRepeatLayout,} = this.props.createStore;
    this.setState({endrepeatOptions: params});
    this.props.history.push(endRepeatLayout.path)
  }

getWorktypeOptions = () => {
  const {workPlanTypeOptions} = this.state;
  let options = [];
  if (workPlanTypeOptions) {
    if (workPlanTypeOptions === 3 || workPlanTypeOptions === '3') {
      options = [{ 'key': '3', 'showname': getLabel(6082,'客户联系') }]//下拉框数据,客户模块的新建
    }else if(workPlanTypeOptions === 2 || workPlanTypeOptions === '2'){
      options = [{ 'key': '2', 'showname': getLabel(16095,'项目日程') }]//下拉框数据,客户模块的新建
    }
  }
  return options;
}

  getFields = () => {
    const { form, selectPage, createInfo,
            setParams,repeatSelectPage,repeatType,remidOptions,
            endrepeatDate,isEdit, } = this.props.createStore;
    const { conditioninfo, isInit} = form;
    const { timeBefore,timeEnd } = createInfo;
    const { workPlanTypeOptions, checked } = this.state;
    const groups = [];
    let value = form.formParams;
    if(isInit) {
      conditioninfo.forEach((group) => {
        const fields = [];
        group.items.forEach((field) => {
          // let options = [];
          if(workPlanTypeOptions !== 0 && field.domkey[0] === "workPlanType") {
            fields.push(
              <Select
                key={'workPlanType'}
                value={workPlanTypeOptions}
                label={field.label}
                options={this.getWorktypeOptions()}
                onChange={(key, showname) => {
                }}
              />
            )
          }
          else if(field.domkey[0] === "remindType") {
            fields.push(
              <SelectPage
                key={'remindtype'}
                options={field.options}
                store={selectPage}
                label={field.label}
                valueArray={remidOptions}
                multiChoose
                onChange={(datas) => {this.getDataKey(datas)}}
              />
            );
           
            if( value['remindType'] !== '' ) {
              (value.repeatType == '0' || value.repeatType == undefined) && fields.push(
                <FormItem 
                  key="immediateRemind"
                  label={getLabel(81917,'立即提醒')}
                  line
                  content={<Switch className="immediateRemind" checked={checked} onClick={(check) => { this.immediateRemind(check) }} />}
                />)
              fields.push(
                <FormItem 
                  key={'starttimebefore'}
                  label={getLabel(19784,'开始前')}
                  wrap="nowrap"
                  line
                  border  
                  required={checked ? false : ((value['remindTimeBeforeStart'] === ''||value['remindTimeBeforeStart'] === 0)&&(value['remindTimeBeforeEnd']===''||value['remindTimeBeforeEnd']===0)) ? true :false}
                  content={(<InputItem id="starttimebefore" editable={false} placeholder={getLabel(19784,'开始前')} time={timeBefore} onClick={(e) => this.onclick(e)} value={this.changeTimeTOLabel(value['remindTimeBeforeStart'], value['remindBeforeStart'])} />)}
                  extra={[<Icon className="starttimebefore"  key="right" type="right" onClick={() => this.onclick({target:{id: 'starttimebefore'}})} />]}
                />,  
                <FormItem 
                  key={'endtimebefore'}
                  label={getLabel(19785,'结束前')}
                  wrap="nowrap"
                  line
                  border  
                  required={checked ? false : ((value['remindTimeBeforeStart'] === ''||value['remindTimeBeforeStart'] === 0)&&(value['remindTimeBeforeEnd']===''||value['remindTimeBeforeEnd']===0)) ? true :false}
                  content={(<InputItem id="endtimebefore" editable={false} placeholder={getLabel(19785,'结束前')} time={timeEnd} onClick={(e) => this.onclick(e) } value={this.changeTimeTOLabel(value['remindTimeBeforeEnd'], value['remindBeforeEnd'])} />)}
                  extra={[<Icon className="endtimebefore" key="right" type="right" onClick={() => this.onclick({target:{id: 'endtimebefore'}})} />]}
                />
              )   
            }
          }else if(field.domkey[0] === "repeatType" || field.domkey[0] === "moudulEndDate") {
            if(field.domkey[0] === "repeatType") {
              let options = [];
              isEdit && field.options && field.options.map(item => { // 周期日程禁选永不（即周期日程禁转普通日程）
                if(item.key !== '0') {
                  options.push(item);
                }
                return '';
              })
              fields.push(
                <SelectPage
                  key={'repeatType'}
                  options={isEdit ? options : field.options}
                  store={repeatSelectPage}
                  label={field.label}
                  valueArray={[repeatType]}
                  onChange={(type) => {this.updateRepeatType(type)}}
                  onItemChange={(key) => {this.getRepeatType(key)}}
                />
              )
            }
            if(field.domkey[0] === "moudulEndDate") {
              fields.push(
              <List.Item
                key={'finishRepeat'}
                extra={endrepeatDate}
                arrow="horizontal"
                onClick={() => {this.getEndRepeat(toJS(field.options))}}
                activeStyle={{'backgroundColor': '#fff'}}
                style={{marginLeft: 6}}
              >
                {field.label}
              </List.Item>
              )
            }
          }
          else if(field.domkey[0] === "beginDateTime" || field.domkey[0] === "endDateTime" ){
            fields.push(
              <DatePicker
                mode="datetime"
                key={field.domkey[0]}
                // value={field.domkey[0]==="beginDateTime" ? beginDateStr : endDateStr}
                value={value[field.domkey[0]]}
                onChange={(date) => {this.setTime(date,field.domkey[0])}}
              >
                <List.Item arrow="horizontal" className={'datepicker'}>{field.label}</List.Item>
              </DatePicker>
            )
          }else{
            if(field.domkey[0] === "meetingId") {
              let meetid = field.browserConditionParam.replaceDatas[0].id;
              setParams({meetingID: meetid});
              return 
            }
            if(field.domkey[0] === "remindBeforeStart" ||field.domkey[0] === "remindBeforeEnd" 
                ||field.domkey[0] === "remindTimeBeforeStart" || field.domkey[0] === "remindTimeBeforeEnd" 
                || field.domkey[0] === "remindImmediately" ){
                return
            }else{
              if(field.domkey[0] === "attachs" && value.repeatType && value.repeatType != '0') {// 普通日程有上传附件字段，周期日程没有
              } else {
                fields.push(
                  <Form.Item
                    key={field.domkey.join('__')}
                    form={form}
                    fieldConfig={field}
                    onChange={this.onChange.bind(this)}
                  />
                );         
              }
            }
          }     
        });
        groups.push(
          // 分组
          <div className='fold-group' key={group.title}>
            <div className='fold-title' onClick={() => {this.handleToggle(group.title, !group.show)}}>
              {group.title}
              <Icon className="flod-icon" type={group.show ? 'up' : 'down'} />
            </div>
            <div className={`${group.show ? 'show' : 'hide'}`}>
              {fields}
            </div>
          </div>
        )
      });
    }else{
      groups.push(
        <div className='loaidng-icon' key='loading'>
          <Icon type='loading' size='lg'/>
        </div>
      )
    }
    return groups;  
  }

  editCondition = ()=>{
    const { form  } = this.props.createStore;
    const { conditioninfo } = form;
    let values = form.formParams
    //判断会议类型
    let conditioninfoTemp = toJS(conditioninfo);
    let retconditioninfo = [];
    let groups = {};
    conditioninfoTemp.length!==0 && conditioninfoTemp.forEach((group) => {
      let fields = []
      group.items.forEach((field) => {
        if(field.conditionType == 'BROWSER'){
          field = this.browserDemand(field, values)
        }

        fields.push(field)
      })
      groups = {...group,items:fields}
      retconditioninfo.push(groups)
    })
    form.setState({conditioninfo:retconditioninfo})
  }

  browserDemand = (oldFields, oldValue)=>{
    let newFields = {...oldFields}
    let newValue = {...oldValue}
    newFields.browserConditionParam.dataParams = {...newFields.browserConditionParam.dataParams,secretLevel: newValue['secretLevel'] ? newValue['secretLevel'] : ''}
    newFields.browserConditionParam.completeParams = {...newFields.browserConditionParam.completeParams,secretLevel: newValue['secretLevel'] ? newValue['secretLevel'] : ''}
    return newFields
  }
  
  handleToggle = (...arg) => {
    const {groupToggle} = this.props.createStore;
    groupToggle(...arg);
  }

  getHeight = () => {
    // let Height = document.body.clientHeight;
    const {isEdit} = this.props.createStore;
    let Height = window.innerHeight;
    
    let btn = document.getElementsByClassName('workplan-create-saveButton')[0];
    if(btn) {
      return isEdit ? Height - btn.offsetHeight - 43.5*window.getThemeVars()['hd'] : Height - btn.offsetHeight;
    }
  }


  render() {
    const { layout, repeatLayout, endRepeatLayout, createDisabled, } = this.props.createStore;
    return(
      <div style={{height:'100%', position: 'relative'}}>
        <div className="workplan-create-list" style={{overflow: 'auto',WebkitOverflowScrolling: 'touch'}}>
          <List>
            {/* 新建{datas} */}
            {this.getFields()}
              <Route
                key={layout.id}
                path={layout.path}
                render={() => (
                  <RouteLayout>
                    <div
                      key='remind'
                      className="wm-route-layout"
                    >
                      <Remind/>
                    </div>
                  </RouteLayout>
                )}
              />    
              <Route
                key={repeatLayout.id}
                path={repeatLayout.path}
                render={() => (
                  <RouteLayout>
                    <div
                      key='repeatType'
                      className="wm-route-layout"
                    >
                      <RepeatType/>
                    </div>
                  </RouteLayout>
                )}
              /> 
              <Route
                key={endRepeatLayout.id}
                path={endRepeatLayout.path}
                render={() => (
                  <RouteLayout>
                    <div
                      key='endRepeat'
                      className="wm-route-layout"
                    >
                      <EndRepeat repeatOptions={this.state.endrepeatOptions} setRepeat={this.setState}/>
                    </div>
                  </RouteLayout>
                )}
              />

          </List>
        </div>
        <div className="workplan-create-saveButton">
          <Button style={{} } disabled={createDisabled} loading={createDisabled} type="primary" onClick={() => {this.submit()}}>{getLabel(386820,'保存')}</Button>
        </div>
        { // 单页新建
          this.state.singleCreate && <RouteCreate />
        } 
      </div>
    );
  }
}

export default Create;